package com.acme.bankapp.domain.bank;

import com.acme.bankapp.domain.bank.exception.ClientExistsException;
import com.acme.bankapp.domain.bank.exception.TooManyClients;
import com.acme.bankapp.domain.bank.exception.TooManyListeners;
import com.sun.javafx.UnmodifiableArrayList;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class Bank {

    private List<Client> clients = new ArrayList<>();

    private ClientRegistrationListener[] listeners = new ClientRegistrationListener[]{c -> System.out.println("Email for client " + c + " was send"),
            c -> System.out.println("Client " + c + " have " + c.getAccount().getMoney()), null, null, null};

    public int getClientNumber() {
        return clients.size();
    }

    private static class DebugListener implements ClientRegistrationListener {
        @Override
        public void onClientAdded(Client c) {
            System.out.println("DEBUG! Client" + c + " was added " + new Date().toString());
        }
    }

    public Bank addRegistrationListener(ClientRegistrationListener l) throws TooManyListeners {
        if (l == null)
            throw new IllegalArgumentException("ClientRegistrationListener is null");
        for (int i = 0; i < listeners.length; i++)
            if (listeners[i] == null) {
                listeners[i] = l;
                return this;
            }
        throw new TooManyListeners();
    }

    public Bank() {
        try {
            addRegistrationListener(new DebugListener());
        } catch (TooManyListeners tooManyListeners) {
            System.out.println("Warning! ClientRegistrationListener[] used at all! Can't add DebugListener!");
        }
    }

    public List<Client> getClients() {
        return Collections.unmodifiableList(clients);
    }

    private void notifyListener(Client client) {
        for (ClientRegistrationListener listener : listeners)
            if (listener != null) {
                listener.onClientAdded(client);
            }
    }

    public Bank addClient(Client client) throws ClientExistsException, TooManyClients {
        clients.add(client);
        notifyListener(client);
        return this;
    }
}
